package com.my.code.samphore;

import java.util.concurrent.TimeUnit;

/**
 * 任务模拟
 *
 * @param <T>
 */
public class CheckTask<T> implements Runnable {
    private static int counter = 0;
    private final int id = counter++;
    private Pool<T> pool;

    public CheckTask(Pool<T> pool) {
        this.pool = pool;
    }

    @Override
    public void run() {
        T t = null;
        try {
            t = pool.checkOut();
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (t != null) {
                System.out.println(this + " finally check in " + t);
                pool.checkIn(t);
            }
        }
    }

    @Override
    public String toString() {
        return "CheckOutTask " + id;
    }
}
